<template>
  <div class="wingknife-executions">
    <div class="page-header">
      <div class="header-left">
        <h2>流程运行管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="fetchExecutionList()" style="margin-right: 10px;">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
        <el-button v-if="fromProcess" type="primary" @click="goToProcessManagement">
          <el-icon><Back /></el-icon>返回流程管理
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-panel">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="流程名称">
          <el-select
            v-model="searchForm.processId"
            placeholder="请选择流程"
            clearable
            filterable
            style="width: 220px"
          >
            <el-option
              v-for="item in processes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 140px"
          >
            <el-option label="等待中" value="pending" />
            <el-option label="运行中" value="running" />
            <el-option label="已完成" value="completed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshRight /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 当前过滤提示 -->
    <div v-if="currentFilterProcessId && processes.length > 0" class="filter-info">
      <el-alert
        type="info"
        :closable="false"
        show-icon
      >
        <template #title>
          当前显示流程 <strong>{{ getProcessName(currentFilterProcessId) }}</strong> 的执行记录
          <el-button type="primary" size="small" text @click="clearExecutionFilter">
            查看所有记录
          </el-button>
        </template>
      </el-alert>
    </div>
        
    <!-- 流程执行记录表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading.executions"
        :data="executions"
        border
        style="width: 100%"
      >
        <el-table-column prop="run_id" label="运行ID" min-width="180" show-overflow-tooltip />
        <el-table-column label="流程名称" min-width="150">
          <template #default="{ row }">
            {{ row.process && row.process.name ? row.process.name : getProcessName(row.process_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="started_at" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.started_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="completed_at" label="完成时间" width="180">
          <template #default="{ row }">
            {{ row.completed_at ? formatDate(row.completed_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" @click="showExecutionDetail(row)">
                <el-icon><View /></el-icon>详情
              </el-button>
              <el-button type="danger" @click="handleDeleteExecution(row)" v-if="row.status !== 'running'">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 执行详情对话框 -->
    <el-dialog
      v-model="dialogs.execution"
      title="执行详情"
      width="750px"
    >
      <div v-if="currentExecution" class="execution-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="运行ID" span="2">{{ currentExecution.run_id }}</el-descriptions-item>
          <el-descriptions-item label="流程名称">{{ currentExecution.process && currentExecution.process.name ? currentExecution.process.name : getProcessName(currentExecution.process_id) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentExecution.status)">
              {{ getStatusText(currentExecution.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDate(currentExecution.started_at) }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ currentExecution.completed_at ? formatDate(currentExecution.completed_at) : '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="center">运行参数</el-divider>
        
        <el-input
          type="textarea"
          :modelValue="JSON.stringify(currentExecution.parameters, null, 2)"
          :rows="12"
          readonly
        />

        <el-divider content-position="center" v-if="currentExecution.result">执行结果</el-divider>
        
        <el-input
          v-if="currentExecution.result"
          type="textarea"
          :modelValue="JSON.stringify(currentExecution.result, null, 2)"
          :rows="8"
          readonly
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Back, View, Delete, Search, RefreshRight, Refresh
} from '@element-plus/icons-vue'
import {
  getWingknifeProcessList,
  getWingknifeExecutionList,
  getWingknifeExecutionDetail,
  deleteWingknifeExecution
} from '@/api/wingknife'

const router = useRouter()
const route = useRoute()

// 状态变量
const processes = ref([])
const executions = ref([])
const currentExecution = ref(null)
const currentFilterProcessId = ref(null)

// 搜索表单
const searchForm = reactive({
  processId: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = reactive({
  executions: false
})

// 对话框显示状态
const dialogs = reactive({
  execution: false
})

// 是否从流程管理页面跳转而来
const fromProcess = computed(() => !!route.query.processId)

// 初始化
onMounted(async () => {
  try {
    const route = useRoute();
    const processId = route.query.processId;
    const processName = route.query.processName;
    
    // 如果有processName参数，说明是从流程管理页面跳转过来的
    if (processName) {
      // 初始化流程列表只包含当前选择的流程
      processes.value = [{
        id: Number(processId),
        name: processName
      }];
      currentFilterProcessId.value = Number(processId);
      await fetchExecutionList(Number(processId));
    } else {
      // 否则获取完整流程列表
      await fetchProcessList();
      await fetchExecutionList();
    }
  } catch (error) {
    console.error('初始化数据失败:', error);
    ElMessage.error('初始化数据失败');
  }
})

// 获取所有流程
const fetchProcessList = async () => {
  try {
    const data = await getWingknifeProcessList()
    processes.value = data
  } catch (error) {
    console.error('获取影刀流程列表失败:', error)
    const errorMessage = error.response?.data?.detail || error.message || '未知错误'
    ElMessage.error(`获取影刀流程列表失败: ${errorMessage}`)
  }
}

// 获取执行记录
const fetchExecutionList = async (processId = null) => {
  loading.executions = true
  try {
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...searchForm
    }
    
    // 如果有特定流程筛选，添加到参数中
    if (processId || currentFilterProcessId.value) {
      params.process_id = processId || currentFilterProcessId.value
    }
    
    const  data  = await getWingknifeExecutionList(params)
    console.log('getWingknifeExecutionList>>>>>', data)
    executions.value = data.items || []
    pagination.total = data.total || 0
  } catch (error) {
    console.error('获取执行记录列表失败:', error)
    // 显示更详细的错误信息
    const errorMessage = error.response?.data?.detail || error.message || '未知错误'
    ElMessage.error(`获取执行记录列表失败: ${errorMessage}`)
    executions.value = []
    pagination.total = 0
  } finally {
    loading.executions = false
  }
}

// 日期格式化
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取执行状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'running': 'warning',
    'completed': 'success',
    'failed': 'danger'
  }
  return types[status] || 'info'
}

// 获取执行状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '等待中',
    'running': '运行中',
    'completed': '已完成',
    'failed': '失败'
  }
  return texts[status] || status
}

// 根据流程ID获取流程名称
const getProcessName = (processId) => {
  // 首先检查当前执行记录列表中是否有关联的流程信息
  const execution = executions.value.find(e => e.process_id === processId);
  if (execution && execution.process && execution.process.name) {
    return execution.process.name;
  }
  
  // 如果没有关联信息，则尝试从流程列表缓存中查找
  const process = processes.value.find(p => p.id === processId);
  return process ? process.name : `流程 #${processId}`;
}

// 清除执行记录过滤
const clearExecutionFilter = () => {
  searchForm.processId = ''
  searchForm.status = ''
  searchForm.dateRange = []
  currentFilterProcessId.value = null
  
  // 重置分页
  pagination.currentPage = 1
  
  // 更新URL
  router.replace({
    query: {}
  })
  
  fetchExecutionList()
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1 // 重置到第一页
  currentFilterProcessId.value = searchForm.processId // 更新当前过滤的流程ID
  fetchExecutionList()
  
  // 更新URL
  const query = {}
  if (searchForm.processId) {
    query.processId = searchForm.processId
    const process = processes.value.find(p => p.id === searchForm.processId)
    if (process) {
      query.processName = process.name
    }
  }
  router.replace({ query })
}

// 重置查询
const resetSearch = () => {
  searchForm.processId = ''
  searchForm.status = ''
  searchForm.dateRange = []
  pagination.currentPage = 1
  
  // 更新URL
  router.replace({
    query: {}
  })
  
  fetchExecutionList()
}

// 显示执行详情
const showExecutionDetail = async (execution) => {
  try {
    const data = await getWingknifeExecutionDetail(execution.id)
    currentExecution.value = data
    dialogs.execution = true
  } catch (error) {
    console.error('获取执行详情失败:', error)
    ElMessage.error('获取执行详情失败')
  }
}

// 删除执行记录
const handleDeleteExecution = async (execution) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除此执行记录吗？删除后不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API删除执行记录
    await deleteWingknifeExecution(execution.id)
    ElMessage.success('删除成功')
    
    // 刷新列表
    fetchExecutionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除执行记录失败:', error)
      ElMessage.error('删除执行记录失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchExecutionList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchExecutionList()
}

// 返回流程管理
const goToProcessManagement = () => {
  router.push('/wingknife')
}

// 运行流程后刷新列表
watch(() => route.query, async (newQuery) => {
  if (newQuery.refresh === 'true') {
    // 移除refresh参数
    const { refresh, ...otherQuery } = newQuery
    router.replace({ query: otherQuery })
    // 刷新列表
    await fetchExecutionList()
  }
}, { deep: true })
</script>

<style scoped>
.wingknife-executions {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0;
}

.search-panel {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.filter-info {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.execution-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
</style> 